import React, { useCallback, useEffect, useMemo, useState } from 'react'
import styled, { css } from 'styled-components'

const Container = styled.div`
    padding: 0 .625rem;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    
`
const SegmentBox = styled.div`
    display: flex;
    align-items: end;
    width: 100%;
`

const Content = styled.div`
    background-color: #5286D2;
    overflow: hidden;
    flex: 1;
`

const Item = styled.div<{ $active?: number, $width?: string }>`
    width: ${({ $width }) => $width || '50%'};
    border-radius: .625rem .625rem 0 0;
    font-weight: normal;
    font-size: 1rem;
    display: flex;
    align-items: center;
    justify-content: center;
    ${({ $active }) => $active ? css`
        background-color: #5286D2;
        color: #ffffff;
        height: 3rem;
    ` : css`
        background-color: #3E73BF;
        color: #ffffffba;
        height: 2.5rem;
    `}
`

export type SegmentItemType = { label: React.ReactNode, key?: string, active?: boolean };
interface Props {
    segments: Array<SegmentItemType>;
    children?: React.ReactNode;
    className?: string;
    onClick?: (item: SegmentItemType, idx: number) => void;
}

const Segment: React.FC<Props> = ({ segments, children, className, onClick }) => {
    const [active, setActive] = useState<string | number>()
    const width = useMemo(() => `${100 / segments.length}%`, [segments.length])

    useEffect(() => {
        if (!segments.length) {
            return
        }

        let idx = segments.findIndex(item => item.active)
        if (idx === -1) {
            idx = 0
        }

        setActive(segments[idx].key || idx)
    }, [segments])

    const itemKey = useCallback((item: SegmentItemType, idx: number) => {
        return item.key || idx
    }, [])

    const handleClick = (item: SegmentItemType, idx: number) => {
        setActive(itemKey(item, idx))
        onClick?.(item, idx)
    }

    return <Container className={className}>
        <SegmentBox>
            {segments.map((item, idx) => <Item
                onClick={() => handleClick(item, idx)}
                key={itemKey(item, idx)}
                $active={Number(active === itemKey(item, idx))}
                $width={width}
            >{item.label}</Item>)}
        </SegmentBox>
        <Content>
            {children}
        </Content>
    </Container>
}

export default Segment